import store from '@/store'
import ViewUI from 'view-design';

//关闭后定时重连计时器
let webSocketReconnectTimeout = null;

if (!("WebSocket" in window)) {
    console.error("该浏览器不支持WebSocket")
}

let telemetry = require('./telemetry.json');
let protobufRoot = require('protobufjs').Root;
let root = protobufRoot.fromJSON(telemetry);
let LiveData = root.lookupType('LiveData');
export const DataList = root.lookupType('DataList');
export const Data = root.lookupType('Data');

const webSocketInit = function () {
    store.state.webSocket.onclose = function () {
        console.debug('WebSocket连接关闭...');
        closeWebSocket();
        webSocketReconnect();
    };
    store.state.webSocket.onerror = function () {
        console.debug("服务地址不可达,WebSocket连接错误...");
    };
    store.state.webSocket.onopen = function () {
        let registerPacket = {
            type: 1,
            userId: Number.parseInt(localStorage.getItem('u-uid')),
            token: localStorage.getItem('u-token')
        }
        //console.log(JSON.stringify(registerPacket))
        store.state.webSocket.send(JSON.stringify(registerPacket));
        if(webSocketReconnectTimeout !== null){
            clearTimeout(webSocketReconnectTimeout);
            webSocketReconnectTimeout = null;
        }
    };
    store.state.webSocket.onmessage = function (evt) {
        if (typeof evt.data === "string"){
            let data = JSON.parse(evt.data);
            let {messageType, state, message, content } = data;
            //注册回复消息
            if (messageType === 1 && state === 100){
                ViewUI.Message.success("实时通信连接建立");
                HeartCheck.reset();
            }
            if (messageType === 1 && state === -102){
                ViewUI.Message.error("账户在其他位置登录...");
                store.state.isLogin = false;
                HeartCheck.clear();
            }
            //险情标记消息
            if (messageType === 4){
                let {dangerLevelId,dangerTypeId,flyTaskId,id,labelImage,lat,lng,projectId,remarks} = content;
                let dangerLevelName;
                if (dangerLevelId===1){
                    dangerLevelName = "一级"
                }
                if (dangerLevelId===2){
                    dangerLevelName = "二级"
                }
                if (dangerLevelId===3){
                    dangerLevelName = "三级"
                }
                ViewUI.Notice.open({
                    title: ' 项目['+projectId+'] '+ '标记'+dangerLevelName+'险情',
                    duration: 120,
                    render: createElement => {
                        return createElement('div', [
                            createElement('div', {
                                style:{
                                    width: '303px',
                                    lineHeight: '24px',
                                    color: '#000000A0',
                                    fontSize: '14px',
                                    padding: '4px 0 2px 0'
                                }
                            },'所属任务ID: '+flyTaskId),
                            createElement('div', {
                                style:{
                                    width: '303px',
                                    lineHeight: '24px',
                                    color: '#000000A0',
                                    fontSize: '14px',
                                    padding: '2px 0 2px 0'
                                }
                            },'类型: '+dangerTypeId),
                            createElement('div', {
                                style:{
                                    width: '303px',
                                    lineHeight: '24px',
                                    color: '#000000A0',
                                    fontSize: '14px',
                                    padding: '2px 0 2px 0'
                                }
                            },'位置: [ '+lng.toFixed(6)+' , '+lat.toFixed(6)+' ]'),
                            createElement('div', {
                                style:{
                                    width: '303px',
                                    lineHeight: '24px',
                                    color: '#000000A0',
                                    fontSize: '14px',
                                    padding: '2px 0 4px 0'
                                }
                            },'备注: '+remarks),
                            createElement('img', {
                                style: {
                                    border: '#5CADFF 1px dashed',
                                    width: '303px'
                                },
                                attrs: {
                                    src: labelImage
                                },
                            })
                        ])
                    }
                });
            }
            //险情处理完成消息
            if (messageType === 5){
                ViewUI.Notice.open({
                    title: ' 险情['+content+' ]已处理',
                });
            }
            // //实时飞行任务相关消息
            if (messageType === 6){
                //status 任务状态 1 任务开始 2 任务结束 3 开始推流 4 结束推流 5 视频存储完成
                let {source,taskNumber,status,uavId,projectId,uavName} = content;
                let statusName;
                let sourceName;
                if (source === 1){
                    sourceName = '云平台'
                }
                if (source === 2){
                    sourceName = '御空'
                }
                switch (status) {
                    case 1:statusName = '任务开始';break
                    case 2:statusName = '任务结束';break
                    case 3:statusName = '开始推流';break
                    case 4:statusName = '结束推流';break
                    case 5:statusName = '视频存储成功';break
                }
                if (status === 1 || status === 2){
                    ViewUI.Notice.open({
                        title: ' 项目['+projectId+'] '+sourceName + ' 无人机['+uavName+']',
                        desc: ' 飞行任务['+taskNumber+']' + statusName,
                        duration: 30
                    });
                }else {
                    ViewUI.Notice.open({
                        title: ' 项目['+projectId+'] '+sourceName + '飞行任务['+taskNumber+'] ' + statusName,
                        duration: 30
                    });
                }
            }
            //用户相关消息
            if (messageType === 10001){
                let {roleId,online,userId,userName,projectId,message} = content;
                let roleName = ""
                if(roleId === 2){
                    roleName = "管理员"
                }
                if(roleId === 3){
                    roleName = "普通用户"
                }
                if(roleId === 4){
                    roleName = "巡线员"
                }
                if (online === 1){
                    ViewUI.Notice.open({
                        title: '项目['+projectId+'] '+roleName+' - '+userName+' 上线',
                        duration: 30
                    });
                }
                if (online === 0){
                    ViewUI.Notice.open({
                        title: '项目['+projectId+'] '+roleName+' - '+userName+' 离线',
                        duration: 30
                    });
                }
            }
        }
        if (typeof evt.data === "object"){
            let reader = new FileReader();
            reader.readAsArrayBuffer(evt.data);
            reader.onload = function () {
                let uavMap = new Map();
                store.state.onlineUavMap.forEach((value, key) => {
                    uavMap.set(key,value)
                })
                let array = new Uint8Array(this.result);
                let message = LiveData.decode(array);
                let telemetry = message.toJSON();
                let {uavId } = telemetry;
                uavMap.set(uavId,telemetry);
                store.state.onlineUavMap = uavMap;
            }
        }
    };
};

const webSocketReconnect = function () {
    if (store.state.seq === Number.parseInt(localStorage.getItem("seq"))){
        if (store.state.isLogin){
            webSocketReconnectTimeout = setTimeout(()=>{
                createWebSocket();
            },2000);
        }
    }else {
        HeartCheck.clear();
    }
};

const HeartCheck = {
    interval: 3000,
    intervalObj: null,
    reset: function(){//接收成功一次推送，就将心跳检测的倒计时重置为30秒
        clearInterval(this.intervalObj);//重置倒计时
        this.start();
    },
    clear: function(){//接收成功一次推送，就将心跳检测的倒计时重置为30秒
        clearInterval(this.intervalObj);//重置倒计时
    },
    start: function(){
        this.intervalObj = setInterval(function(){
            let message = {
                type: 2,
                userId: Number.parseInt(localStorage.getItem('u-uid'))
            };
            if (store.state.webSocket.readyState === WebSocket.OPEN){
                store.state.webSocket.send(JSON.stringify(message));
            }
        },this.interval)
    }
};

//登录成功时开启WebSocket, 设置事件操作
export function createWebSocket () {
    try {
        store.state.webSocket = new WebSocket(store.state.webSocketUrl);
    } catch (e) {
        console.debug("WS连接服务器异常");
    }
    webSocketInit();
}

//退出登录时关闭WebSocket, 清楚心跳定时器
export function closeWebSocket(){
    store.state.webSocket.close();
    HeartCheck.clear();
}